<?php
//   +----------------------------------------------------------------------
//   | Copyright (c) 2015-2025 http://www.hdphp.cn All rights reserved.
//   | Licensed ( http://www.hdphp.cn/licenses/ )
//   | Author: Jack <sophia2152@qq.com>
//   | 官方网址: http://www.hdphp.cn
//   | 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用。
//   | 任何企业和个人不允许对程序代码以任何形式任何目的再发布。
//   +----------------------------------------------------------------------
namespace hdphp\services\wechat;

use hdphp\services\wechat\config\OpenWebConfig;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Exceptions\BadRequestException;
use EasyWeChat\Kernel\Exceptions\InvalidArgumentException;
use EasyWeChat\Kernel\Exceptions\InvalidConfigException;
use EasyWeChat\OpenPlatform\Application;
use Symfony\Component\Cache\Adapter\RedisAdapter;
use Symfony\Component\HttpFoundation\Request;
use think\facade\Cache;
use think\Response;
use Yurun\Util\Swoole\Guzzle\SwooleHandler;

/**
 * Class：开放平台
 * 创建人：Jack
 * 创建时间：2023/12/11 10:52
 * @package hdphp\services\wechat
 */
class OpenPlatform extends BaseApplication
{
    /**
     * @var OpenWebConfig
     */
    protected $config;

    /**
     * @var Application
     */
    protected $application;

    /**
     * OpenPlatform constructor.
     */
    public function __construct()
    {
        /** @var OpenWebConfig config */
        $this->config = app()->make(OpenWebConfig::class);
        $this->debug = DefaultConfig::value('logger');
    }

    /**
     * @return OpenPlatform
     */
    public static function instance()
    {
        return app()->make(static::class);
    }

    /**
     * @return Application
     */
    public function application()
    {
        if (!$this->application) {
            $this->application = Factory::openPlatform($this->config->all());
            $request = request();
            $this->application['guzzle_handler'] = SwooleHandler::class;
            $this->application->rebind('request', new Request($request->get(), $request->post(), [], [], [], $request->server(), $request->getContent()));
            $this->application->rebind('cache', new RedisAdapter(Cache::store('redis')->handler()));
        }
        return $this->application;
    }

    /**
     * 服务端
     * @return Response
     * @throws BadRequestException
     * @throws InvalidArgumentException
     * @throws InvalidConfigException
     * @throws \ReflectionException
     */
    public static function serve(): Response
    {
        $make = self::instance();
        $make->application()->server->push($make->pushMessageHandler);
        $response = $make->application()->server->serve();
        return response($response->getContent());
    }

}
